//
//  LZWebViewController.m
//  LZHundredJie
//
//  Created by apple on 16/4/6.
//  Copyright © 2016年 m14a.cn. All rights reserved.
//

#import "LZWebViewController.h"
#import <WebKit/WebKit.h>

@interface LZWebViewController ()

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** webView*/
@property (nonatomic, weak) WKWebView *webView;

@end

@implementation LZWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.创建WKWebView对象
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    // 2.请求数据
    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
    [webView loadRequest:request];
    // 3.添加上去
//    [self.view addSubview:webView];
    _webView = webView;
    // 好好咀嚼,消化完毕,如果是addSubview:webView,那么progressView下标是0,webView下标是1
    // 所以会挡住
    // [self.view insertSubview:webView atIndex:0],那么progressView下标是1,progressView在webView上面，也就没有被挡住
    [self.view insertSubview:webView atIndex:0];
    
    // 添加监听者
    // KVO: 让self对象监听webView的estimatedProgress
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

// 只要监听的属性有新值就会调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    // 1.赋值
    self.progressView.progress = self.webView.estimatedProgress;
    // 2.隐藏
    self.progressView.hidden = self.progressView.progress >= 1;
}

// KVO一定要移除观察者
- (void)dealloc
{
    // 移除监听者
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
